package org.jeecg.modules.demo.single.controller;

import java.io.InputStream;
import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.io.IOUtils;
import org.bouncycastle.crypto.paddings.ZeroBytePadding;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.util.JwtUtil;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.base.entity.ZnzfEmployee;
import org.jeecg.modules.demo.base.service.IZnzfEmployeeService;
import org.jeecg.modules.demo.definedtool.Paging;
import org.jeecg.modules.demo.single.entity.ZnzfNeedSingle;
import org.jeecg.modules.demo.single.entity.ZnzfNeedSingleVo;
import org.jeecg.modules.demo.single.service.IZnzfNeedSingleService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.flowable.controller.FlowModelController;
import org.jeecg.modules.flowable.dto.FlowInstanceStartDTO;
import org.jeecg.modules.flowable.dto.FlowTaskOperationDTO;
import org.jeecg.modules.flowable.entity.FlowInstance;
import org.jeecg.modules.flowable.entity.FlowModel;
import org.jeecg.modules.flowable.query.FlowTaskQuery;
import org.jeecg.modules.flowable.service.FlowInstanceService;
import org.jeecg.modules.flowable.service.FlowModelService;
import org.jeecg.modules.flowable.service.FlowTaskService;
import org.jeecg.modules.flowable.vo.FlowInstanceVO;
import org.jeecg.modules.flowable.vo.FlowTaskVO;
import org.jeecg.modules.system.entity.SysRole;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysRoleService;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

 /**
 * @Description: 单身宿舍申请
 * @Author: jeecg-boot
 * @Date:   2022-03-29
 * @Version: V1.0
 */
@Api(tags="单身宿舍申请")
@RestController
@RequestMapping("/single/znzfNeedSingle")
@Slf4j
public class ZnzfNeedSingleController extends JeecgController<ZnzfNeedSingle, IZnzfNeedSingleService> {

	@Autowired
	private IZnzfNeedSingleService znzfNeedSingleService;

	 @Autowired
	 private ISysUserService sysUserService;

	 @Autowired
	 private IZnzfEmployeeService znzfEmployeeService;

	 @Autowired
	 private ISysUserRoleService sysUserRoleService;

	 @Autowired
	 private ISysRoleService sysRoleService;

	 @Autowired
	 private FlowInstanceService flowInstanceService;

	 @Autowired
	 private FlowModelService flowModelService;

	 @Autowired
	 private FlowTaskService flowTaskService;

	 @ApiOperation(value = "znzf_need_single-审核单身公寓申请",notes = "通过或拒绝")
	 @PostMapping(value = "/passOrDeny")
	 public Result<String> passOrDeny(HttpServletRequest request, @RequestBody JSONObject jsonObject){
		 String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		 String name = JwtUtil.getUsername(token);
		 SysUser sysUser = sysUserService.getUserByName(name);
		 String id = jsonObject.getString("id");
		 ZnzfNeedSingle znzfNeedSingle = znzfNeedSingleService.getById(id);
		 ZnzfEmployee znzfEmployee = znzfEmployeeService.getById(znzfNeedSingle.getEid());
		 int step = znzfNeedSingle.getStep();
		 boolean inCheckRole = znzfNeedSingleService.isInCheckRole(name,znzfNeedSingleService.intToRolename(step));
		 Result<String> result = new Result();
		 if(!inCheckRole){
		 	result.setSuccess(false);
		 	result.setMessage("不是对应角色,无法审核!");
		 	return result;
		 }
		 String uid = sysUserService.getUserByName(name).getId();
		 int ret = jsonObject.getIntValue("ret");
		 String note = jsonObject.getString("note");


		 FlowTaskQuery flowTaskQuery = new FlowTaskQuery();
		 // 设置查询用户信息
		 flowTaskQuery.setUserId(sysUser.getId());
		 // 部门id
		 flowTaskQuery.setDeptIds(Collections.singletonList(sysUser.getDepartIds()));
		 // 角色id
		 List<SysUserRole> sysUserRoleList = sysUserRoleService.searchbyuserId(sysUser.getId());
		 List<String> roleIds = new ArrayList<>();
		 for(SysUserRole sysUserRole : sysUserRoleList){
		 	roleIds.add(sysUserRole.getRoleId());
		 }
		 flowTaskQuery.setRoleIds(roleIds);
		 Result<Page<FlowTaskVO>> pageResult = flowTaskService.todoList(flowTaskQuery);
		 List<FlowTaskVO> flowTaskVOList = pageResult.getResult().getRecords();
		 FlowTaskVO flowTaskVO = new FlowTaskVO();
		 for(FlowTaskVO flowTaskVO1 : flowTaskVOList){
			 System.out.println(flowTaskVO1.getProcessInstanceId()+ "\n");
			 if(flowTaskVO1.getBusinessKey().equals("singleApartApply") || flowTaskVO1.getBusinessDataId().equals(znzfEmployee.getUserId() + "-" + znzfNeedSingle.getId())){
				 flowTaskVO = flowTaskVO1;
				 break;
			 }
		 }
		 // 7、审核流程
		 FlowTaskOperationDTO operationDTO = new FlowTaskOperationDTO();

		 // 审批处置人
		 operationDTO.setUserId(sysUser.getId());
		 operationDTO.setUserName(sysUser.getRealname());
		 // 审批节点
		 operationDTO.setProcessInstanceId(flowTaskVO.getProcessInstanceId());
		 operationDTO.setTaskId(flowTaskVO.getTaskId());



		 if(step < 4){
		 	int  updateRet = znzfNeedSingleService.checkApply(step,id,uid,ret,note);
		 	if(updateRet <= 0)
		 		return Result.error("审核错误!");
		 	else if(updateRet == 1){
				operationDTO.setMessage("审批通过");
				flowTaskService.complete(operationDTO);
			}
			else if(updateRet == 2){
				operationDTO.setMessage("审批拒绝");
				flowTaskService.veto(operationDTO);
			}
		 	result.setSuccess(true);
		 	result.setMessage("审核成功!");
		 	return result;
		 }
		 int updateRet = znzfNeedSingleService.checkApplyLastStep(step,id,uid,ret,note);
		 if(updateRet <= 0)
			 return Result.error("审核错误或分配房源错误!");
		 else if(updateRet == 1){
			 operationDTO.setMessage("审批通过");
			 flowTaskService.complete(operationDTO);
		 }
		 else if(updateRet == 2){
			 operationDTO.setMessage("审批拒绝");
			 flowTaskService.veto(operationDTO);
		 }
		 result.setSuccess(true);
		 result.setMessage("分配房源成功!");



		 return result;
	 }

	 /**
	  * 用户申请报名
	  * @param request
	  * @param jsonObject
	  * @return
	  */
	 @ApiOperation(value = "znzf_need_single-点击报名按钮",notes = "用户报名提示的信息")
	 @PostMapping(value = "/checkapplyinfo")
	 public Result<JSONObject> userApplyButtonMsg(HttpServletRequest request, @RequestBody JSONObject jsonObject){
	 	 String projectId = jsonObject.getString("projectId");
		 String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		 String name = JwtUtil.getUsername(token);
		 String uid = sysUserService.getUserByName(name).getId();
		 return Result.OK(znzfNeedSingleService.applyMessage(projectId,uid));
	 }

	/**
	 * 分页列表查询
	 *
	 * @param znzfNeedSingle
	 * @param pageNo
	 * @param pageSize
	 * @param req
	 * @return
	 */
	//@AutoLog(value = "单身宿舍申请-分页列表查询")
	@ApiOperation(value="单身宿舍申请-分页列表查询", notes="单身宿舍申请-分页列表查询")
	@GetMapping(value = "/list")
	public Result<IPage<ZnzfNeedSingle>> queryPageList(ZnzfNeedSingle znzfNeedSingle,
								   @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
								   @RequestParam(name="pageSize", defaultValue="10") Integer pageSize,
								   HttpServletRequest req) {
		QueryWrapper<ZnzfNeedSingle> queryWrapper = QueryGenerator.initQueryWrapper(znzfNeedSingle, req.getParameterMap());
		Page<ZnzfNeedSingle> page = new Page<ZnzfNeedSingle>(pageNo, pageSize);
		IPage<ZnzfNeedSingle> pageList = znzfNeedSingleService.page(page, queryWrapper);
		return Result.OK(pageList);
	}

	 /**
	  * 根据token查询用户申请房源状态
	  *
	  * @return
	  */
	 //@AutoLog(value = "单身宿舍申请-根据token查询用户申请房源状态")
	 @ApiOperation(value="单身宿舍申请-根据token查询用户申请房源状态", notes="单身宿舍申请-根据token查询用户申请房源状态")
	 @PostMapping(value = "/searchByToken")
	 public Result<ZnzfNeedSingle> searchByToken(HttpServletRequest request) {
		 String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		 String name = JwtUtil.getUsername(token);
		 SysUser sysUser = sysUserService.getUserByName(name);
		 ZnzfEmployee znzfEmployee = znzfEmployeeService.searchByUid(sysUser.getId());
		 ZnzfNeedSingle znzfNeedSingle = znzfNeedSingleService.searchByEid(znzfEmployee.getId());
		 if(oConvertUtils.isEmpty(znzfNeedSingle))
		 	return Result.error("该用户还未申请房源");
		 return Result.OK(znzfNeedSingle);
	 }

	 /**
	  * 管理员通过部门编码进行分页列表查询
	  *
	  * @param pageNo
	  * @param pageSize
	  * @param request
	  * @return
	  */
	 //@AutoLog(value = "单身宿舍申请-管理员通过部门编码进行分页列表查询")
	 @ApiOperation(value="单身宿舍申请-管理员通过部门编码进行分页列表查询", notes="单身宿舍申请-管理员通过部门编码进行分页列表查询")
	 @GetMapping(value = "/listByOrgCode")
	 public Result<Page<ZnzfNeedSingleVo>> queryPageList(HttpServletRequest request, @RequestParam(name="pageNo", defaultValue="1") Integer pageNo,
														@RequestParam(name="pageSize", defaultValue="10") Integer pageSize) {
		 String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		 String name = JwtUtil.getUsername(token);
		 SysUser sysUser = sysUserService.getUserByName(name);
		 List<SysUserRole> sysUserRolelist = sysUserRoleService.searchbyuserId(sysUser.getId());
		 List<ZnzfNeedSingleVo> znzfNeedSingleVoList = new ArrayList<>();
		 int[] roles = new int[5];
		 Paging<ZnzfNeedSingleVo> page = new Paging<>();
		 int tmp = 0;
		 for(SysUserRole sysUserRole : sysUserRolelist){
			 SysRole sysRole = sysRoleService.getById(sysUserRole.getRoleId());
			 String code = sysRole.getRoleCode();
			 char c = code.charAt(code.length() - 1);
			 switch (c){
				 case'1':{
					 roles[tmp] = 1;
					 tmp++;
				 }break;
				 case'2':{
					 roles[tmp] = 2;
					 tmp++;
				 }break;
				 case'3':{
					 roles[tmp] = 3;
					 tmp++;
				 }break;
				 case'4':{
					 roles[tmp] = 4;
					 tmp++;
				 }break;
			 }
		 }
		 if(oConvertUtils.isEmpty(roles))
		 	return page.getPaging(null,pageNo,pageSize);
		 for(int role : roles){
			 List<ZnzfNeedSingleVo> res = znzfNeedSingleService.listByOrgCode(role);
			 if(oConvertUtils.isNotEmpty(res)){
				 znzfNeedSingleVoList.addAll(res);
			 }
		 }
//		 String OrgCode = sysUser.getOrgCode();
//		 char c = OrgCode.charAt(OrgCode.length() - 1);
//		 Integer step = Integer.parseInt(String.valueOf(c));
//		znzfNeedSingleVoList = znzfNeedSingleService.listByOrgCode(step);

		 Result<Page<ZnzfNeedSingleVo>> result = page.getPaging(znzfNeedSingleVoList,pageNo,pageSize);
		 return result;
	 }
	
	/**
	 *   添加
	 *
	 * @param znzfNeedSingle
	 * @return
	 */
	@AutoLog(value = "单身宿舍申请-添加")
	@ApiOperation(value="单身宿舍申请-添加", notes="单身宿舍申请-添加")
	@PostMapping(value = "/add")
	public Result<String> add(@RequestBody ZnzfNeedSingle znzfNeedSingle) {
		znzfNeedSingleService.save(znzfNeedSingle);
		return Result.OK("添加成功！");
	}

	 /**
	  *   职工添加房源申请
	  *
	  * @param znzfNeedSingle
	  * @return
	  */
	 @AutoLog(value = "单身宿舍申请-职工添加房源申请")
	 @ApiOperation(value="单身宿舍申请-职工添加房源申请", notes="单身宿舍申请-职工添加房源申请")
	 @PostMapping(value = "/insert")
	 public Result<String> insert(HttpServletRequest request,@RequestBody ZnzfNeedSingle znzfNeedSingle) {
		 String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		 String name = JwtUtil.getUsername(token);
		 SysUser sysUser = sysUserService.getUserByName(name);
		 ZnzfEmployee znzfEmployee = znzfEmployeeService.searchByUid(sysUser.getId());
		 if(oConvertUtils.isEmpty(znzfEmployee))
			 return Result.error("没有职工信息");
		 if(oConvertUtils.isNotEmpty(znzfEmployee.getRoomId()))
		 	return Result.error("当前已有住房");
		 znzfNeedSingle.setStep(1);
		 znzfNeedSingle.setEid(znzfEmployee.getId());
		 znzfNeedSingle.setIsEnd(0);
		 int res = znzfNeedSingleService.insert(znzfNeedSingle);
		 if(res == 0)
		 	return Result.error("当前还有住房申请");

		 FlowInstanceStartDTO startDTO = new FlowInstanceStartDTO();
		 // 设置流程发起用户
		 startDTO.setUserId(sysUser.getId());
		 startDTO.setUserName(sysUser.getRealname());
		 // 设置发起表单信息 --> 模型定义的业务标识
		 startDTO.setBusinessKey("singleApartApply");
		 // 表单对应的唯一标识（用于区分不同的业务流程申请）
		 startDTO.setBusinessDataId(sysUser.getId() + "-" + znzfNeedSingle.getId());
		 // 表单参数（可以直接将DTO或ENTITY序列化为JSON）
		 Map<String, Object> map = new HashMap<>();
		 map.put("time", LocalDateTime.now());
		 startDTO.setBusinessData(JSONUtil.toJsonStr(map));
		 flowInstanceService.start(startDTO);
		 return Result.OK("添加成功！");
	 }

//	 @AutoLog(value = "单身宿舍申请-查看流程图")
//	 @ApiOperation(value="单身宿舍申请-查看流程图", notes="单身宿舍申请-查看流程图")
//	 @PostMapping(value = "/searchFlow")
//	 public Result<Page<FlowTaskVO>> searchFlow(HttpServletRequest request) {
//		 FlowTaskQuery flowTaskQuery = new FlowTaskQuery();
//		 String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
//		 String name = JwtUtil.getUsername(token);
//		 SysUser sysUser = sysUserService.getUserByName(name);
//		 if(oConvertUtils.isEmpty(sysUser))
//		 	return Result.error("账号异常");
//		 // 待办查询
//		 // FlowTaskQuery flowTaskQuery = new FlowTaskQuery();
//		 // 设置查询用户信息
//		 flowTaskQuery.setUserId(sysUser.getId());
//		 // 部门id
//		 flowTaskQuery.setDeptIds(Collections.singletonList(sysUser.getDepartIds()));
//		 // 角色id
//		 List<SysUserRole> sysUserRoleList = sysUserRoleService.searchbyuserId(sysUser.getId());
//		 if(oConvertUtils.isEmpty(sysUserRoleList))
//		 	return Result.error("账号角色异常");
//		 List<FlowTaskVO> flowTaskVOList = new ArrayList<>();
//		 for(SysUserRole sysUserRole : sysUserRoleList){
//			 System.out.println(sysUserRole.getRoleId());
//			 flowTaskQuery.setRoleIds(Collections.singletonList(sysUserRole.getRoleId()));
//			 Result<Page<FlowTaskVO>> pageResult = flowTaskService.todoList(flowTaskQuery);
//			 System.out.println(pageResult.getResult().toString() + "\n");
//			 System.out.println(pageResult.getResult().getRecords().toString() + "\n");
//			 if(oConvertUtils.isEmpty(pageResult.getResult().getRecords()))
//			 	continue;
//			 flowTaskVOList.addAll(pageResult.getResult().getRecords());
//		 }
//		 Paging<FlowTaskVO> result = new Paging<>();
//		 //flowTaskQuery.setRoleIds(Collections.singletonList(sysUserRoleService.searchbyuserId(sysUser.getId())));
//		 //FlowTaskVO flowTaskVO = pageResult.getResult().getRecords().get(0);
//		 return result.getPaging(flowTaskVOList,1,10);
//	 }

	 @AutoLog(value = "单身宿舍申请-查看流程图")
	 @ApiOperation(value="单身宿舍申请-查看流程图", notes="单身宿舍申请-查看流程图")
	 @PostMapping(value = "/searchFlow")
	 public Result<FlowInstanceVO> searchFlow(HttpServletRequest request,HttpServletResponse response,@RequestBody JSONObject jsonObject) throws IOException {
	 	FlowTaskQuery flowTaskQuery = new FlowTaskQuery();
		String token = request.getHeader(CommonConstant.X_ACCESS_TOKEN);
		String name = JwtUtil.getUsername(token);
		SysUser sysUser = sysUserService.getUserByName(name);
		ZnzfEmployee znzfEmployee = znzfEmployeeService.searchByUid(sysUser.getId());
		if(oConvertUtils.isEmpty(sysUser))
			return Result.error("账号异常");
		String id = jsonObject.getString("id");
		ZnzfNeedSingle znzfNeedSingle = znzfNeedSingleService.searchByEidAndProjectId(znzfEmployee.getId(), id);
		 System.out.println(sysUser.getId() + "-" + znzfNeedSingle.getId() + "\n");
		FlowInstance flowInstance = flowInstanceService.searchByBusinessKeyAndBusinessDataId("singleApartApply", sysUser.getId() + "-" + znzfNeedSingle.getId());
		 System.out.println(flowInstance + "\n");
		if(oConvertUtils.isEmpty(flowInstance))
			return Result.error("当前没有相关流程");
		InputStream inputStream = flowModelService.genProcessDiagramSchedule(flowInstance.getId());
		response.setHeader("Content-type", "image/png");
		IOUtils.copy(inputStream, response.getOutputStream());
		inputStream.close();
		 Result<FlowInstanceVO> res = flowInstanceService.info(flowInstance.getId());
		 System.out.println(res.getResult());
		 return res;
	 }

	/**
	 *  编辑
	 *
	 * @param znzfNeedSingle
	 * @return
	 */
	@AutoLog(value = "单身宿舍申请-编辑")
	@ApiOperation(value="单身宿舍申请-编辑", notes="单身宿舍申请-编辑")
	@RequestMapping(value = "/edit", method = {RequestMethod.PUT,RequestMethod.POST})
	public Result<String> edit(@RequestBody ZnzfNeedSingle znzfNeedSingle) {
		znzfNeedSingleService.updateById(znzfNeedSingle);
		return Result.OK("编辑成功!");
	}
	
	/**
	 *   通过id删除
	 *
	 * @param id
	 * @return
	 */
	@AutoLog(value = "单身宿舍申请-通过id删除")
	@ApiOperation(value="单身宿舍申请-通过id删除", notes="单身宿舍申请-通过id删除")
	@DeleteMapping(value = "/delete")
	public Result<String> delete(@RequestParam(name="id",required=true) String id) {
		znzfNeedSingleService.removeById(id);
		return Result.OK("删除成功!");
	}
	
	/**
	 *  批量删除
	 *
	 * @param ids
	 * @return
	 */
	@AutoLog(value = "单身宿舍申请-批量删除")
	@ApiOperation(value="单身宿舍申请-批量删除", notes="单身宿舍申请-批量删除")
	@DeleteMapping(value = "/deleteBatch")
	public Result<String> deleteBatch(@RequestParam(name="ids",required=true) String ids) {
		this.znzfNeedSingleService.removeByIds(Arrays.asList(ids.split(",")));
		return Result.OK("批量删除成功!");
	}
	
	/**
	 * 通过id查询
	 *
	 * @param id
	 * @return
	 */
	//@AutoLog(value = "单身宿舍申请-通过id查询")
	@ApiOperation(value="单身宿舍申请-通过id查询", notes="单身宿舍申请-通过id查询")
	@GetMapping(value = "/queryById")
	public Result<ZnzfNeedSingle> queryById(@RequestParam(name="id",required=true) String id) {
		ZnzfNeedSingle znzfNeedSingle = znzfNeedSingleService.getById(id);
		if(znzfNeedSingle==null) {
			return Result.error("未找到对应数据",null);
		}
		return Result.OK(znzfNeedSingle);
	}

    /**
    * 导出excel
    *
    * @param request
    * @param znzfNeedSingle
    */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, ZnzfNeedSingle znzfNeedSingle) {
        return super.exportXls(request, znzfNeedSingle, ZnzfNeedSingle.class, "单身宿舍申请");
    }

    /**
      * 通过excel导入数据
    *
    * @param request
    * @param response
    * @return
    */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, ZnzfNeedSingle.class);
    }

}
